/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) {
        queue<Node*> queueNode;
        if (root == NULL) {
            return root;
        }

        queueNode.push(root);
        Node* curFront = NULL;
        while (!queueNode.empty()) {
            int levelSize = queueNode.size();
            for (int idx = 0; idx < levelSize; idx++) {
                curFront = queueNode.front();
                queueNode.pop();
                if (idx < levelSize - 1) {
                    curFront->next = queueNode.front();
                }
                if (curFront->left != NULL) {
                    queueNode.push(curFront->left);
                }
                if (curFront->right != NULL) {
                    queueNode.push(curFront->right);
                }
            }
        }
        return root;
    }
};